package com.topscomm.main.aspect;

import com.topscomm.cbo.pojo.CboSystemErrorLogEntity;
import com.topscomm.cbo.service.ICboSystemErrorLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.http.HttpServletRequest;

/**
 * 当记录错误日志时，同时记录请求url以及参数
 */
@Aspect
@Component
@Slf4j
public class ErrorLogEnhance {
    @Autowired
    ICboSystemErrorLogService cboSystemErrorLogService;

    public ErrorLogEnhance() {
    }

    //定义切入为CboSystemErrorLogService的writeLog方法
    @Pointcut("execution(* com.topscomm.cbo.service.impl.CboSystemErrorLogService.writeLog(..))&&args(java.lang.Throwable)")
    public void logCut() {
    }

    //返回后 获取当前请求上下文，请求url，请求参数及路径，并保存到错误日志实体类中
    @AfterReturning(pointcut = "logCut()", returning = "errlog")
    public void getLogInfo(JoinPoint joinPoint, CboSystemErrorLogEntity errlog) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) {
                return;
            }
            HttpServletRequest servletRequest = attributes.getRequest();
            ContentCachingRequestWrapper requestWrapper = (ContentCachingRequestWrapper) servletRequest;
            StringBuilder stringBuilder = new StringBuilder();
            //获取当前线程请求url 请求参数 请求body
            stringBuilder.append("请求url:").append(requestWrapper.getRequestURL()).append("\n");
            stringBuilder.append("请求参数:").append(requestWrapper.getQueryString()).append("\n");
            stringBuilder.append("请求body:").append(new String(requestWrapper.getContentAsByteArray())).append("\n");
            errlog.setExtendfield1(stringBuilder.substring(0,stringBuilder.length()));
            cboSystemErrorLogService.updateEntity(errlog);
        } catch (Exception e) {
            log.error("获取请求信息失败", e);
        }
    }
}
